package com.momoauth.common.security.aspect;

import com.momoauth.common.security.annotation.RequiresPermissions;
import com.momoauth.common.security.dao.RolePermsDao;
import com.momoauth.common.core.exception.GlobalException;
import com.momoauth.common.security.entity.Role_Perms;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;

import javax.annotation.Resource;
import java.lang.reflect.Method;

@Aspect
@Order(3)
public class RequiresPermissionsAspect {

    @Resource
    RolePermsDao rolePermsDao;

    /**
     * 拦截方法进行操作权限判断
     * @param joinPoint
     * @return
     */
    @Around("@annotation(com.momoauth.common.security.annotation.RequiresPermissions)")
    public Object Interceptor(ProceedingJoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        RequiresPermissions requiresPermissions = method.getAnnotation(RequiresPermissions.class);
        if (!handleRolePermissions(requiresPermissions)) {
            throw new GlobalException(50001,"很抱歉，操作权限不足。");
        }
        Object result = null;
        try {
            result = joinPoint.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 操作权限判断处理
     * @param requiresPermissions
     * @return
     */
    private boolean handleRolePermissions(RequiresPermissions requiresPermissions) {
        Role_Perms role_perms = null;
        switch (requiresPermissions.logical()) {
            case OR:
                for (String perms : requiresPermissions.value()) {
                    role_perms = rolePermsDao.getSingleRolePerms(perms);
                    if (role_perms != null && role_perms.getValue().equals(perms)) {
                        return true;
                    }
                }
                return false;
            case AND:
                for (String perms : requiresPermissions.value()) {
                    role_perms = rolePermsDao.getSingleRolePerms(perms);
                    if (role_perms == null) {
                        return false;
                    }
                }
                return true;
        }
        return false;
    }
}
